import TIM from './tim-wx'
import TIMUploadPlugin from './tim-upload-plugin'
import { setStorage, getStorage, getTimUserId } from '../utils'
import request from '../request'
import api from '../../config/api'

export default {
  // 获取用户签名
  async getUserSig() {
    const userSigCache = getStorage('userSig')
    if (userSigCache) {
      return userSigCache
    }
    const userid = getTimUserId(getStorage('userId'))
    const userSig = await request.get(api.imUserSig, { userid })
    setStorage('userSig', userSig)
    return userSig
  },
  // tim初始化
  init() {
    if (wx.$TUIKit) return
    wx.$TUIKit = TIM.create({ SDKAppID: 1400585518 })
    wx.$TUIKit.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin })
    wx.$TUIKitTIM = TIM
    wx.$TUIKitEvent = TIM.EVENT
    wx.$TUIKitVersion = TIM.VERSION
    wx.$TUIKitTypes = TIM.TYPES
    wx.$TUIKitLogin = false
    wx.$TUIKitReady = false
    // 监听系统级事件
    wx.$TUIKit.on(wx.$TUIKitEvent.SDK_NOT_READY, function (e) {
      console.log('tim sdk 还没有准备好', e)
    })
    wx.$TUIKit.on(wx.$TUIKitEvent.KICKED_OUT, function (e) {
      wx.showToast({
        title: '您被踢下线',
        icon: 'error',
      })
      console.log('您被踢下线', e)
    })
    wx.$TUIKit.on(wx.$TUIKitEvent.ERROR, function (e) {
      console.log('tim报错：', e)
    })
    wx.$TUIKit.on(wx.$TUIKitEvent.NET_STATE_CHANGE, function (e) {
      console.log('tim网络变化', e)
    })
    wx.$TUIKit.on(wx.$TUIKitEvent.SDK_RELOAD, function (e) {
      console.log('tim sdk 重启', e)
    })
  },
  // tim登录
  async login() {
    const vm = this
    if (wx.$TUIKitLogin && wx.$TUIKitReady) {
      return true
    }
    if (!getStorage('userId') || !getStorage('userSig')) {
      wx.showToast({
        icon: 'none',
        title: '您还没有登录im',
      })
      return false
    }
    const res = await wx.$TUIKit.login({
      userID: getTimUserId(getStorage('userId')),
      userSig: getStorage('userSig'),
    })
    console.log('tim登录信息：', res)
    const isReady = await new Promise((resolve) => {
      if (wx.$TUIKitReady) {
        resolve(true)
      } else {
        wx.$TUIKit.on(wx.$TUIKitEvent.SDK_READY, async function (e) {
          wx.$TUIKitReady = true
          await vm.updateUser()
          resolve(true)
          console.log('tim sdk 已经准备好', e)
        })
      }
    })
    wx.$TUIKitLogin = res.data.actionStatus === 'OK'
    return isReady && wx.$TUIKitLogin
  },
  // 获取会话列表
  async getMessageList() {
    if (!wx.$TUIKitReady) {
      return []
    }
    const res = await wx.$TUIKit.getConversationList()
    console.log('会话列表：', res)
    return res.data.conversationList
  },
  // 连接会话
  connect(callback) {
    wx.$TUIKit.on(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, (event) => {
      console.log('会话列表更新：', event)
      callback(event.data)
    })
  },
  // 断开会话
  disconnect(callback) {
    wx.$TUIKit.off(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, (event) => {
      console.log('会话列表更新：', event)
      callback(event.data)
    })
  },
  // 获取用户
  async getUser(userId) {
    if (!wx.$TUIKitReady) {
      wx.showToast({
        title: 'im还没有准备好',
        icon: 'none',
      })
      return null
    }
    const imRes = await wx.$TUIKit.getUserProfile({
      userIDList: [userId],
    })
    console.log('tim用户信息', imRes)
    if (imRes.data.length > 0) {
      return imRes.data[0]
    } else {
      wx.showToast({
        title: 'im用户不存在',
        icon: 'none',
      })
      return null
    }
  },
  // 更新用户信息
  async updateUser() {
    if (!wx.$TUIKitReady) return
    const { nickName, avatarUrl } = getStorage('userInfo') || {}
    const res = await wx.$TUIKit.updateMyProfile({
      nick: nickName,
      avatar: avatarUrl,
    })
    console.log('更新im用户信息：', res)
  },
  // 获取会话对象
  async getConversation(conversationID) {
    const res = await wx.$TUIKit.getConversationProfile(conversationID)
    const { conversation } = res.data
    let conversationName = ''

    if (conversation.type === '@TIM#SYSTEM') {
      conversationName = '系统通知'
    }
    if (conversation.type === 'C2C') {
      conversationName = conversation.remark || conversation.userProfile.nick || conversation.userProfile.userID
    }
    if (conversation.type === 'GROUP') {
      conversationName = conversation.groupProfile.name || conversation.groupProfile.groupID
    }

    return {
      conversationName,
      conversation,
    }
  },
  // 设置已读
  setRead(conversationID) {
    wx.$TUIKit.setMessageRead({ conversationID }).then(() => {
      console.log(conversationID, '信息已读')
    })
  },
}